package com.coderman.generateSqlBatchTools.service;

import com.coderman.generateSqlBatchTools.bean.ColumnBean;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * Created by ${fanchunshuai} on 2017-4-9.
 *
 * @version: V1.0
 * @Desc: 基于两种接口实现过程中所需要处理的公共步骤封装到该类中
 * @Copyright (c) 2017 58到家-版权所有
 */
public class GenerateHelper {

    private static Logger logger = Logger.getLogger(GenerateHelper.class);


    /**
     * 对生成的sql string进行统一的数据处理
     * @param dataType
     * @param builder
     * @param outFilePath
     */
    public static  boolean  resultDataManage(int dataType,StringBuilder builder,String outFilePath) throws IOException {
        if(dataType == 1){
            logger.error("-----error...............");
            logger.info("is't success ,the generate sqlBatchContent as below:");
            logger.info("------------------------------------------  sql start ------------------------------------------");
            logger.info(builder.toString());
            logger.info("------------------------------------------  sql end ------------------------------------------");


        }
        //打印到控制台
        else if(dataType == 2){
            logger.info("is't success ,the generate sqlBatchContent will print out in console... ");
            System.out.println(builder.toString());
        }

        else if(dataType == 3 && StringUtils.isNotBlank(outFilePath)){
            logger.info("is't success ,the generate sqlBatchContent will write to specified file... ");
            FileUtils.writeStringToFile(new File(outFilePath),builder.toString(),"UTF-8");
        }else{
            logger.error("is't failed ,the specified file path is null or the dataType doesn't equals 1,2,3.... ");
            return false;
        }
        return true;
    }

    /**
     * 由于生成sql的有方法都会进行下面的校验检查，因此统一封装了一层
     * @param fromIndex
     * @param rows
     * @param tableName
     * @param columnBeanMap
     * @return
     */
    public static boolean checkParams(int fromIndex,int rows ,String tableName,Map<String, ColumnBean> columnBeanMap){
        if(StringUtils.isBlank(tableName)){
            logger.error("table name is null,please check the param list... ");
            return false;
        }

        if(fromIndex < 0 || fromIndex >= rows){
            logger.error("read excel from index is out of range,please check the excel and the param list... ");
            return false;
        }

        if(columnBeanMap.isEmpty()){
            logger.error("columnBeanMap is empty ,please check the param list...  ");
            return false;
        }
        return true;
    }


}
